﻿using QRCodeBluetooth.DAL;
using QRCodeBluetooth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QRCodeBluetooth.BUS
{
    public class ProjectBUS
    {
        public ResponseMessage AddProject(ProjectInfo projectInfo)
        {
            ResponseMessage message = new ResponseMessage();
            ProjectDAL da = new ProjectDAL();
            string regcode = GenerateRandomNumber(6);
            while (da.CheckReg(regcode) > 0)
            {
                regcode = GenerateRandomNumber(6);
            }
            projectInfo.project_code = regcode;
            bool result = da.AddProject(projectInfo);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "新增项目信息失败";
            }
            return message;
        }

        private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
        public static string GenerateRandomNumber(int Length)
        {
            StringBuilder newRandom = new StringBuilder(62);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(36)]);
            }
            return newRandom.ToString();
        }

        public ResponseMessage EditProject(ProjectInfo projectInfo)
        {
            ResponseMessage message = new ResponseMessage();
            ProjectDAL da = new ProjectDAL();

            bool result = da.EditProject(projectInfo);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "修改项目信息失败";
            }
            return message;
        }

        public ResponseMessage DeleteProject(ProjectInfo projectInfo)
        {
            ResponseMessage message = new ResponseMessage();
            ProjectDAL da = new ProjectDAL();

            bool result = da.DeleteProject(projectInfo);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "删除项目信息失败";
            }
            return message;
        }

        public ResponseMessage QueryProject(ProjectInfo projectInfo)
        {
            ResponseMessage message = new ResponseMessage();
            ProjectDAL da = new ProjectDAL();
            message.errcode = 0;
            message.data = da.QueryProject(projectInfo);
            message.total = da.QueryProjectCount(projectInfo);

            return message;
        }
    }
}
